package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: WJW
 * Date: 2024-10-10
 * Time: 19:47
 */
public class Utils {
    public static WebDriver driver;
    public static WebDriver createDriver(){
        if(driver == null){
            WebDriverManager.chromedriver().setup();
            ChromeOptions options = new ChromeOptions();
            //允许访问所有连接
            options.addArguments("--remote-allow-origins=*");

            driver = new ChromeDriver(options);

            //隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));
        }
        return driver;
    }

    public Utils(String url){
        //调用driver对象
        driver = createDriver();
        //访问URL
        driver.get(url);
    }
    //屏幕截图进阶版
    void getScreenShot(String str) throws IOException, IOException {

        //  ./src/test/image/
        //                  /2024-10-09/
        //                             /test01-13363034.png
        //                             /test02-13363034.png
        //                  /2024-10-10/
        //                             /test01-13363045.png
        //                             /test02-13363034.png



        //屏幕截图
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");//精确到毫秒防止被覆盖

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        //./src/test/image/2024-10-9/test01-13363043.png
        String filename ="./src/test/image/"+ dirTime +"/" + str + "-" + fileTime+".png";
        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        //srcFile放到指定位置
        FileUtils.copyFile(srcFile,new File(filename));

    }
}
